Skip to content

[lexical-table] Bug Fix: use visual line detection instead of caret rect for cell exit in arrow key handling - #9393

Open
lou-magnenat wants to merge 13 commits into
meta:mainfrom
Infomaniak:fix/table-caret-line-detection-soft-wrap
Open

lou-magnenat wants to merge 13 commits into
meta:mainfrom
Infomaniak:fix/table-caret-line-detection-soft-wrap

Conversation

@lou-magnenat

@lou-magnenat lou-magnenat commented Oct 20, 2026 •

Copy link
Copy Markdown

Description

$handleArrowKey decides whether a vertical arrow key leaves the table cell by comparing the caret's rect (the DOM selection range's getBoundingClientRect()) with the cell's edge child box. At a soft wrap the caret sits between two visual lines, and a collapsed range there reports its bounding rect at the end of the previous line in every engine (it is the first of the client rects). With the caret logically at the start of a cell's last visual line:

  • ArrowDown skipped the hijack on Chromium and the native movement landed in the cell to the right (document order) instead of the one below; Gecko moves below natively, masking the bug.
  • ArrowUp hijacked the caret out of the table in every engine, instead of moving up one visual line within the cell.

Rather than guess the caret's affinity, which the DOM does not expose, this change detects the ambiguous wrap boundary and defers to the engine:

  • getVisualLineRectAtCaret measures the caret's visual line through its adjacent character: the rect of the character to the right (last client rect, so a range spanning the wrap boundary reports the line it ends on), falling back to the character to the left when the caret ends its text node, and to the collapsed range's own rect when nothing can be measured (jsdom, hidden editor).
  • When the adjacent character renders on a different line than the caret's rect (more than 4px on top), the position is ambiguous: the keypress arms a one-shot pendingVerticalExit and returns false so the native movement runs with the engine's own affinity. The next selection change consumes it and corrects the landing with selectTableNodeInDirection only when the caret left the original cell's column; a landing in the same column or inside the original cell's subtree (a nested table under the cell's text, for example) is trusted.
  • A pointer interaction, or any subsequent keydown or blur, clears a pending exit.
  • The consuming selection change corrects only when the DOM selection moved off the armed caret: the engine moves the DOM selection before Lexical dispatches the command for it, while a change made by code or a collaborator dispatches before reconciliation writes the DOM selection, so an armed intent whose native movement never happened (a modifier combo that moves nothing, for instance) can neither redirect an unrelated change nor correct with a grid whose armed cell was removed.

Known limitations, documented in the code: a wrap whose next line starts a new text node (a formatted word, for example) is not detected as ambiguous, the deferral is collapsed-caret only (with shift, the pre-existing caret-rect behavior applies), and in a first-row cell, ArrowUp from the end of the first visual line defers to the engine and moves to the start of that line, a second ArrowUp exiting the table.

Test plan

Before

New browser test packages/lexical-table/src/__tests__/browser/WrappedTextCellArrowKeys.test.ts fails without the fix.

Chromium:

❯ |browser (chromium)| packages/lexical-table/src/__tests__/browser/WrappedTextCellArrowKeys.test.ts (8 tests | 2 failed) 1960ms
  × ArrowDown from the start of the last visual line moves to the cell below
    AssertionError: expected 'c5' to be 'c7'
  × ArrowUp from the start of the second visual line stays in the cell
    AssertionError: expected 'c1' to be 'c4 aaabbb cccddd'

Firefox:

❯ |browser (firefox)| packages/lexical-table/src/__tests__/browser/WrappedTextCellArrowKeys.test.ts (8 tests | 1 failed) 1948ms
  × ArrowUp from the start of the second visual line stays in the cell
    AssertionError: expected 'c1' to be 'c4 aaabbb cccddd'

Repro: any table cell whose text soft-wraps, caret at a wrap boundary, ArrowDown (Chromium) or ArrowUp (any engine).

After

Test Files  8 passed (8)
     Tests  68 passed (68)   // pnpm run test-browser packages/lexical-table (chromium)
Test Files 21 passed (21)
    Tests  216 passed (216) // pnpm run test-unit packages/lexical-table

WrappedTextCellArrowKeys.test.ts also passed on Firefox (automated review, at the previous head). The two code-driven tests and the wait rework added since have not run on a local Firefox: the Playwright Firefox install on the author's machine no longer launches (unrelated to this change). The suite runs on CI.

@meta-cla

meta-cla Bot commented Oct 20, 2026

Copy link
Copy Markdown

Hi @lou-magnenat!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks!

@vercel

vercel Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
lexical Ready Ready Preview Nov 17, 2026 8:43am UTC
lexical-playground Ready Ready Preview Nov 17, 2026 8:43am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 21, 2026
@meta-cla

meta-cla Bot commented Oct 21, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed write-up and the browser test. The start-of-line case is real, and the new test reproduces it: before this change, ArrowUp from the start of a wrapped cell's second line leaves the table, and in Chromium ArrowDown from the start of the last line lands in the cell to the right.

One problem needs fixing before this can land, plus one smaller one:

1. A caret at the end of a wrapped line now goes the wrong way (packages/lexical-table/src/LexicalTableSelectionHelpers.ts:2424-2437, :2726-2727)

At a soft wrap, "end of line N" and "start of line N+1" are the same DOM position: same text node, same offset. Only the caret's affinity differs, and the DOM doesn't expose it. The old code always assumed the end of line N; getVisualLineRectAtCaret always assumes the start of line N+1. So a caret placed at the end of a wrapped line, by End or by clicking past the line's last word, is now treated as being on the next line. With the test's 3×3 table and a two-line c4:

Caret placed by Key Before After
Home on line 2 ArrowDown c5 ✗ c7 ✓
Home on line 2 ArrowUp c1 ✗ stays in c4 ✓
End on line 1 (or a click past its end) ArrowDown line 2 of c4 ✓ c7 ✗ (Chromium and Firefox)
End on line 1 (or a click past its end) ArrowUp c1 ✓ c3 ✗ (Chromium)

The ArrowUp case also happens in cells of three or more lines. Could you detect the ambiguous case (the collapsed-range rect and the adjacent-character rect sit on different lines) and resolve it without a fixed guess? One option is to let the native movement run and correct a landing outside the cell's column. Please also add End or click-past-end cases for both keys to WrappedTextCellArrowKeys.test.ts.

2. The jsdom fallback described in the comment doesn't happen (:2433)

jsdom's Range has no getClientRects, and the repository's vitest.setup.mts stubs only getBoundingClientRect. So with a collapsed caret inside a cell's text, the ArrowUp and ArrowDown commands now hit TypeError: characterRange.getClientRects is not a function instead of falling back as the comment at :2721-2725 says. Test setups that stub only getBoundingClientRect (what the old code needed) hit the same error. A typeof characterRange.getClientRects === 'function' guard, plus a unit case under __tests__/unit (the tier AGENTS.md assigns to jsdom behaviour), would keep that promise.

Optional, non-blocking:

  • The two-line precondition (WrappedTextCellArrowKeys.test.ts:283, :298) depends on "c4 aaabbb" fitting the 75px cell in the browser's default serif font. With a wider fallback such as DejaVu, the cell renders three lines and both main tests fail at that assertion. Choosing the offsets per line (ArrowUp from the start of line 2, ArrowDown from the start of the last line) makes the test independent of the line count, and the fix already handles three-line cells correctly.
  • A wrap where the second line starts a new text node (a bold word, for example) is still mis-detected. Lexical normalizes the caret to the end of the previous text node, and the helper then measures the trailing space that hangs on line 1. You could handle that case by measuring the next sibling's first character, or note it in the comment.

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for reworking this. The change looks good: deferring to the browser's own move at an ambiguous wrap, then correcting a landing outside the cell's column, fixes the start-of-line cases without breaking the end-of-line ones. Home, End and clicks on either side of a wrap all reached the right line or cell in Chromium, and the new browser tests fail without this change and pass with it in Chromium and Firefox. The getClientRects guard and the per-line test offsets also address the earlier comments.

All of the following are optional and non-blocking:

  1. A deferred exit that nothing consumes can redirect a later selection change (packages/lexical-table/src/LexicalTableSelectionHelpers.ts:2794-2810). The core editor dispatches KEY_ARROW_UP_COMMAND/KEY_ARROW_DOWN_COMMAND with Alt held, and on Linux and Windows Alt+ArrowUp/Down doesn't move the caret. So pendingVerticalExit stays armed until the next selection change, from the keyboard or from code. With the caret at the start of c4's last line in your test table, Alt+ArrowDown then Tab lands in c7 instead of c5, and Alt+ArrowDown then Ctrl+End lands in c7 instead of c9 (Chromium and Firefox). Clearing the flag in the existing capture-phase keydown listener in registerTableWindowHandlers, next to clearTouchTap, fixes both and keeps your tests green. A browser test for Alt+ArrowDown then Tab would lock it in. The same file already guards this kind of stale flag for shouldCheckSelectionForTable.
  2. Changeset after rebasing. CONTRIBUTING.md on current main now asks for a changeset for every user-facing change, for example '@lexical/table': patch with [fix] Arrow keys at a soft wrap in a table cell move to the right line or cell and a Verify: line.
  3. PR description and Test plan. They still describe the first revision: 5 tests, a test name that no longer exists, and an "unchanged" exit comparison with no mention of the native-move deferral. AGENTS.md ("Commits and Pull Requests") asks for the real Before/After output of the command you ran.
  4. Minor edge case. In a first-row cell of a table that is the first block, End on line 1 then ArrowUp now moves the caret to the start of line 1 instead of leaving the table. A second ArrowUp exits.

Automated review (maintainer link)

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this — the change looks good to me. Deferring to the browser's own line movement at an ambiguous wrap and correcting only a landing that leaves the cell's column fixes both directions, and the new browser tests fail without the change and pass with it in Chromium and Firefox. The suggestions below are optional and non-blocking.

  1. A pending exit can outlive a key that moved nothing (packages/lexical-table/src/LexicalTableSelectionHelpers.ts:1352-1397). pendingVerticalExit is consumed by the next SELECTION_CHANGE_COMMAND of any origin, and core dispatches that for every committed selection change, so the keydown/pointerdown/blur clearing does not cover a change made by code or by a collaborator. After Alt+ArrowDown (which moves no caret on Linux and Windows) from the start of c4's last line, selecting c5 inside editor.update lands in c7, and removing c4's row and the row below throws Node at cords not TableCellNode. from selectTableNodeInDirection, so that update is discarded. Returning early when originCellNode is no longer a TableCellNode removes the throw; correcting only once the DOM selection has moved off the armed caret would leave code-driven changes alone, since $notifyPendingSelectionChange runs before reconciliation writes the DOM selection. A browser test that presses Alt+ArrowDown and then changes the selection in editor.update would pin it.
  2. Document the first-row case where readers will look (.changeset/table-soft-wrap-arrow-keys.md:7). The PR description notes that in a first-row cell with nothing above the table, ArrowUp from the end of the first line now moves to the start of that line and a second press leaves the table. The changeset's Verify: line says End and clicks keep their behavior, and .changeset/README.md (on main) describes Verify: as what people upgrading should test; one sentence about this edge there or in the comment at LexicalTableSelectionHelpers.ts:2785-2796 would cover it.
  3. Test waits (packages/lexical-table/src/__tests__/browser/WrappedTextCellArrowKeys.test.ts:148, :155, :251, :289, :388). Every wait is a fixed 60 ms sleep; waiting for the expected selection instead would be sturdier on a loaded runner.

The CI workflows for this head are waiting for a maintainer to approve them, so they have not run yet.

Automated review (maintainer link)

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. Thanks for the careful write-up and for the real-browser regression test. Everything below is optional and non-blocking.

What I checked

  • On the base source, WrappedTextCellArrowKeys.test.ts fails 2 of 10 cases in Chromium (expected 'c5' to be 'c7', expected 'c1' to be 'c4 aaabbb cccddd') and 1 in Firefox, which matches your Before output. On this head all 10 pass in both Chromium and Firefox, including the two code-driven tests you couldn't run on Firefox locally.
  • The packages/lexical-table browser and unit suites pass (133 and 216 tests). The branch merges cleanly into current main, and those suites stay green there.
  • The earlier points are addressed at this head: End/click affinity at the end of a wrapped line, the jsdom getClientRects fallback, Alt+ArrowDown leaving an exit armed, and code-driven selection changes. For example, Alt+ArrowDown followed by Tab now lands in c5.

Optional suggestion

  • packages/lexical-table/src/__tests__/browser/WrappedTextCellArrowKeys.test.ts:521: "a code-driven update that removes the armed cell is not discarded by the exit correction" still passes when the $isTableCellNode(originCellNode) check is removed from $handleTableSelectionChangeCommand (LexicalTableSelectionHelpers.ts:1393). The DOM selection never moves in that test, so the nativeMovement check already voids the correction. If you move the DOM selection off the armed caret before the removing update, the test exercises that guard: it passes as written and throws Node at cords not TableCellNode. without the guard.
// after dispatching the Alt+ArrowDown keydown, before editor.update(...)
window.getSelection()!.collapse(getDomText(editor, c5Key), 0);

Here c5Key is the key of c5's text node.

The first-row case, where ArrowUp from the end of the first line needs a second press when the table starts the document, is a trade-off the changeset documents, so I'm not raising it as an issue.

The CI workflows for this head are still waiting for maintainer approval, so CI results are pending.

Automated review (maintainer link)

expect(anchorText(editor)).toBe('c5');
});

test('a code-driven update that removes the armed cell is not discarded by the exit correction', async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this test stays green when $isTableCellNode(originCellNode) is removed from $handleTableSelectionChangeCommand (LexicalTableSelectionHelpers.ts:1393). The DOM selection never moves here, so the nativeMovement check already voids the correction. If you move the DOM selection off the armed caret before the removing update, for example with window.getSelection()!.collapse(getDomText(editor, c5Key), 0) using c5's text key, the test reaches that guard: it passes on this head and throws Node at cords not TableCellNode. without the guard.

This branch was successfully deployed

2 active deployments
Preview – lexical — d57811ce Deployed Nov 17, 2026 by vercel[bot]
Preview – lexical-playground — d57811ce Deployed Nov 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant